package geppetto.cat.corpus;

import gnu.trove.TObjectIntHashMap;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;

public class LanguageVocab {
	public TObjectIntHashMap<String> _wordToId;
	public ArrayList<String> _idToWord;	
	int _size;
	
	public LanguageVocab() {
		super();
		_idToWord = new ArrayList<String>();
		_wordToId = new TObjectIntHashMap<String>();
		_size = 0;
	}

	public void addWord(String word){
		if(!_wordToId.contains(word)){
			_wordToId.put(word, _size);
			_idToWord.add(word);
			_size++;
		}
	}
	
	public void addSentence(String[] words){
		for(String word : words){
			addWord(word);
		}
	}
	
	public int getWordId(String word){
		return _wordToId.get(word);
	}
	
	public String getWordFromId(int id){
		return _idToWord.get(id);
	}
	
	public int[] getSentenceIds(String[] words){
		int[] sentenceIds = new int[words.length];
		for(int i = 0; i < sentenceIds.length; i++){
			sentenceIds[i] = getWordId(words[i]);
		}
		return sentenceIds;
	}

	public int[] getSentenceIdsReverse(String[] words) {
		int[] sentenceIds = new int[words.length];
		for(int i = 0; i < sentenceIds.length; i++){
			sentenceIds[i] = getWordId(words[sentenceIds.length - i - 1]);
		}
		return sentenceIds;
	}
	
	public String[] getSentenceFromIds(int[] wordIds) {
		String[] sentence = new String[wordIds.length];
		for(int i = 0; i < sentence.length; i++){
			sentence[i] = getWordFromId(wordIds[i]);
		}
		return sentence;		
	}
	
	public String getSentence(Object[] objects) {
		String sentence = "";
		for(int i = 0; i < objects.length; i++){
			sentence += objects[i];
			if(i!=objects.length-1){
				sentence+= " ";
			}
		}
		return sentence;	
	}
	
	public void buildVocabFromLMFile(BufferedReader reader) throws IOException {
		while(reader.ready()){
			String line = reader.readLine();
			String[] words = line.split("\\t");
			if(words.length > 1){
				String ngram = words[1];
				String[] ngram_words = ngram.split("\\s+");
				addSentence(ngram_words);
			}
		}
	}

	public void buildVocabFromTextFile(BufferedReader reader) throws IOException {
		while(reader.ready()){
			String line = reader.readLine();
			String[] words = line.split("\\s+");
			addSentence(words);
		}
	}
}
